from typing import Annotated

from fastapi import Query, Body
from pydantic import model_validator

from app.utils import types
from app.models.common import AppId, Pagination, TrialRecordId
from app.models import responses


class AppTrialRecordList(AppId, Pagination):
    """分页获取指定应用的试用记录"""
    device_code: str
    trial_ip: str

    @model_validator(mode='before')
    @classmethod
    def before(cls, data):
        data = types.safe_dict(data)
        data['device_code'] = data.get('device_code', '')
        data['trial_ip'] = data.get('trial_ip', '')
        return data

    @model_validator(mode='after')
    def after(self):
        if len(self.device_code) > 128:
            raise responses.FailureResponseError(-102, msg='设备码长度不能超过 128 位')

        if len(self.trial_ip) > 64:
            raise responses.FailureResponseError(-102, msg='试用 IP 长度不能超过 64 位')

        return self


AppTrialRecordListParams = Annotated[AppTrialRecordList, Query()]


class UpdateTrialCount(TrialRecordId):
    """修改已试用次数"""
    trial_count: int = 0

    @model_validator(mode='before')
    @classmethod
    def before(cls, data):
        data = types.safe_dict(data)
        data['trial_count'] = types.safe_int(data.get('trial_count', None), -1)
        return data

    @model_validator(mode='after')
    def after(self):
        if not (0 <= self.trial_count <= 255):
            raise responses.FailureResponseError(-102, msg='试用次数的范围只能是 0-255')

        return self


UpdateTrialCountJSON = Annotated[UpdateTrialCount, Body()]
